package ocr

import (
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/config"
	"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	documentautoml20221229 "github.com/alibabacloud-go/documentautoml-20221229/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *documentautoml20221229.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("documentautoml.cn-beijing.aliyuncs.com")
	_result = &documentautoml20221229.Client{}
	_result, _err = documentautoml20221229.NewClient(config)
	return _result, _err
}

func Predict(pdfUrl string, modelId int64) (*documentautoml20221229.PredictModelResponse, error) {
	// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html
	client, _err := CreateClient(tea.String(config.C.OpenSearchIndustry.AccessKeyId), tea.String(config.C.OpenSearchIndustry.AccessKeySecret))
	if _err != nil {
		return nil, _err
	}

	predictModelRequest := &documentautoml20221229.PredictModelRequest{
		BinaryToText: tea.Bool(false),

		Content: tea.String(pdfUrl),
		ModelId: tea.Int64(modelId),
	}
	runtime := &util.RuntimeOptions{}
	tryErr, res := func() (_e error, res *documentautoml20221229.PredictModelResponse) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		res, _err := client.PredictModelWithOptions(predictModelRequest, runtime)
		if _err != nil {
			log.Error("返回ocr数据失败：err:", _err.Error())
			return _err, nil
		}
		return nil, res
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		_, _err := util.AssertAsString(error.Message)
		if _err != nil {
			log.Error("tryErr返回ocr数据失败：err:", _err.Error())
			return nil, _err
		}
	}
	return res, nil
}
